import { UserModel } from '../../schemas/system/User';
import { User } from '../../types';
import { HttpError } from '../../exceptions/HttpError';

export class UserRepository {
  // 获取所有用户
  async findAll(): Promise<User[]> {
    try {
      return await UserModel.find().select('-password').sort({ createdAt: -1 }).populate('createdBy updatedBy tenantId').lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`获取用户列表失败: ${error.message}`);
    }
  }



  // 根据ID获取用户
  async findById(id: string): Promise<User | null> {
    try {
      const user = await UserModel.findById(id).select('-password').populate('createdBy updatedBy tenantId').lean();
      if (!user) {
        throw HttpError.notFound('用户不存在');
      }
      return user;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取用户信息失败: ${error.message}`);
    }
  }

  // 根据邮箱查找用户
  async findByEmail(email: string): Promise<User | null> {
    try {
      return await UserModel.findOne({ email });
    } catch (error: any) {
      throw HttpError.internalServerError(`查找用户失败: ${error.message}`);
    }
  }

  // 创建用户
  async create(userData: Partial<User>): Promise<User> {
    try {
      const user = new UserModel(userData);
      return await user.save();
    } catch (error: any) {
      if (error.code === 11000) {
        throw HttpError.conflict('邮箱已被注册');
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败1', error.errors);
      }
      throw HttpError.internalServerError(`创建用户失败2: ${error.message}`);
    }
  }

  // 更新用户
  async update(id: string, userData: Partial<User>): Promise<User | null> {
    try {
      // 移除密码字段，防止通过更新接口修改密码
      const { password, ...updateData } = userData;

      const user = await UserModel.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      ).select('-password');

      if (!user) {
        throw HttpError.notFound('用户不存在');
      }

      return user;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      if (error.code === 11000) {
        throw HttpError.conflict('邮箱已被注册');
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败', error.errors);
      }
      throw HttpError.internalServerError(`更新用户失败: ${error.message}`);
    }
  }

  // 删除用户
  async delete(id: string): Promise<boolean> {
    try {
      const result = await UserModel.findByIdAndDelete(id);
      if (!result) {
        throw HttpError.notFound('用户不存在');
      }
      return true;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除用户失败: ${error.message}`);
    }
  }

  // 获取用户数量
  async count(): Promise<number> {
    try {
      return await UserModel.countDocuments();
    } catch (error: any) {
      throw HttpError.internalServerError(`统计用户数量失败: ${error.message}`);
    }
  }

  // 分页查询用户
  async findWithPagination(page: number = 1, limit: number = 10): Promise<{ list: User[], page: number, limit: number, total: number, pages: number }> {
    try {
      const skip = (page - 1) * limit;
      const [list, total] = await Promise.all([
        UserModel.find().select('-password').sort({ createdAt: -1 }).skip(skip).limit(limit).populate('createdBy updatedBy tenantId').lean(),
        UserModel.countDocuments()
      ]);

      return {
        list,
        total,
        page,
        limit,
        pages: Math.ceil(total / limit)
      };
    } catch (error: any) {
      throw HttpError.internalServerError(`分页查询用户失败: ${error.message}`);
    }
  }
}

export default new UserRepository();